package com.aim.analysis.artifact;

import com.aim.analysis.records.Hit;
import com.aim.azure.AzureConnection;
import com.aim.util.filters.Filter;

import java.io.File;
import java.net.URISyntaxException;
import java.security.InvalidKeyException;
import java.util.*;

/**
 * User: Avraham Shvartzon
 * Date: 7/24/14
 */
public class ArtifactManager {

    private final File rootFolder;
    private final List<AbstractArtifact> artifacts = new ArrayList<AbstractArtifact>();
    EnumSet<ExperimentDate> experimentDates = EnumSet.allOf(ExperimentDate.class);
    private Filter<Hit> filter;

    public ArtifactManager(File rootFolder) {
        this.rootFolder = rootFolder;
    }

    public void setExperimentDates(ExperimentDate... experimentDates){
        List<ExperimentDate> experimentDatesList = Arrays.asList(experimentDates);
        this.experimentDates = EnumSet.copyOf(experimentDatesList);
    }

    public void addArtifact(AbstractArtifact artifact){
        artifacts.add(artifact);
    }

    public boolean execute() throws Exception {
        AzureConnection azureConnection = new AzureConnection();
        azureConnection.connect();

        Set<String> tableSuffixes = new HashSet<String>();
        for (ExperimentDate experimentDate : experimentDates) {
            tableSuffixes.add(experimentDate.tableSuffix);
        }
        List<Hit> hits = Hit.getHits(tableSuffixes.toArray(new String[0]));

        hits = filterHits(hits);
        Collections.sort(hits, new Comparator<Hit>() {
            @Override
            public int compare(Hit o1, Hit o2) {
                return o1.getDate().compareTo(o2.getDate());
            }
        });

        for (AbstractArtifact artifact : artifacts) {
            artifact.setRootFolder(rootFolder);
            artifact.execute(hits);
        }
        return true;
    }

    private List<Hit> filterHits(List<Hit> hits) {
        if (filter == null){
            return hits;
        }
        List<Hit> filteredList = new ArrayList<Hit>();
        for (Hit hit : hits) {
            if (filter.accept(hit)){
                filteredList.add(hit);
            }
        }
        return filteredList;
    }


    public void addHitFilter(Filter<Hit> filter) {
        this.filter = filter;
    }
}
